package com.sgcc.pda.web.upload.asynctask;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.sgcc.pda.baselibrary.utils.LogUtil;
import com.sgcc.pda.mdrh.app.ZoomApplication;
import com.sgcc.pda.newsm4.SM4Utils;
import com.sgcc.pda.sdk.utils.ConstantSM4;
import com.sgcc.pda.sdk.utils.DataConversionUtil;
import com.sgcc.pda.sdk.utils.ZoomSPUtils;
import com.sgcc.pda.sdk.utils.db.SharepreferenceUtil;
import com.sgcc.pda.web.upload.entity.BlockUploadParams;
import com.sgcc.pda.web.upload.entity.BlockUploadResponse;
import com.sgcc.pda.web.upload.entity.ReturnString;
import com.sgcc.pda.web.upload.okhttp.OkHttpSyncResponse;
import com.sgcc.pda.web.upload.okhttp.OkhttpUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashMap;
import java.util.Map;

import static com.sgcc.pda.sdk.utils.ConstantSM4.SM4_IV;
import static com.sgcc.pda.sdk.utils.ConstantSM4.SM4_KEY;


/**
 * @author zcj
 * @date 2019/10/4
 * 解析随文件上传的参数
 * 针对单块文件封装
 */
public class UploadAsyncTask extends AsyncTask<Void, Void, String> {

    private static final String TAG = "cj";
    //后台存储地址，业务传来的
    private String savePath;
    //一块
    private byte[] content;
    private BlockListener blockListener;
    private BlockUploadParams params;
    private String tempFilePath;
    private final int currentBlockNo;

    public UploadAsyncTask(String savePath, byte[] content, BlockUploadParams params, BlockListener blockListener) {
        this.savePath = savePath;
        this.content = content;
        this.params = params;
        this.blockListener = blockListener;

        tempFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + params.getFileName() + ".temp";
        currentBlockNo = params.getCurrentBlockNo();
    }

    @Override
    protected String doInBackground(Void... voids) {
//        boolean connected = NetWorkUtil.getInstance().isConnected(MyApplication.getInstance());
//        if(!connected){}

//        Map<String, String> map = new HashMap<>();
//        map.put("currentBlockNo", "" + params.getCurrentBlockNo());
//        map.put("blockSum", "" + params.getBlockSum());
//        map.put("rangeKey", params.getRangeKey());
//        map.put("fileSize", "" + params.getFileSize());
//        map.put("fileMd5", "" + params.getFileMd5());

        String url = getUrl(ZoomApplication.getInstance()) + "reqHttpFileUp.do";
        StringBuilder sb = new StringBuilder();
        sb.append("uploadBigFile");
        sb.append("?");
        sb.append("currentBlockNo=");
        sb.append(params.getCurrentBlockNo());
        sb.append("&blockSum=");
        sb.append(params.getBlockSum());
        sb.append("&rangeKey=");
        sb.append(params.getRangeKey());
        sb.append("&fileSize=");
        sb.append(params.getFileSize());
        sb.append("&fileMd5=");
        sb.append(params.getFileMd5());
        sb.append("&fileName=");
        sb.append(params.getFileName());
        sb.append("&UID=");
        sb.append(SharepreferenceUtil.getUid(ZoomApplication.getInstance()));
        sb.append("&MAC=");
        sb.append("12345");
        if (!TextUtils.isEmpty(savePath)) {
            sb.append("&filePath=");
            sb.append(savePath);
        }
        String requestParms = sb.toString();

        Map<String, String> map = new HashMap<>();
        map.put("SERVER_NAME", "upfileserver");
        if (ZoomSPUtils.getEncryption()) {
            try {
                String s = SM4Utils.encryptData_CBC(ConstantSM4.SM4_KEY, ConstantSM4.SM4_IV, DataConversionUtil.str2HexStr(requestParms));
                map.put("REQUEST_PARM", s);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            map.put("REQUEST_PARM", DataConversionUtil.str2HexStr(requestParms));
        }

        OkHttpSyncResponse okHttpSyncResponse = OkhttpUtils.getInstance().multipartPost(url, params.getFileName() + params.getRangeKey(), params.getFileName(), map, content);

        if (okHttpSyncResponse.isSuccessful()) {
            return okHttpSyncResponse.getResponse();
        } else {
            return okHttpSyncResponse.getErrorMsg();
        }

    }

    @Override
    protected void onPostExecute(String response) {
        LogUtil.e(TAG, "onPostExecute: " + response);
        if (ZoomSPUtils.getEncryption()) {
            try {
                response = SM4Utils.decryptData_CBC(SM4_KEY, SM4_IV, response);
                response = DataConversionUtil.hexStr2Str(response);
                LogUtil.e(TAG, "解密数据: " + response);
//                HzLogSaveUtil.saveLog("解密数据：" + response, HzLogSaveUtil.LogType.WEB);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Gson gson = new Gson();
        try {

            BlockUploadResponse uploadResponse = gson.fromJson(response, BlockUploadResponse.class);

            //链路失败
            if (uploadResponse == null) {

                writeTempFile(2);
                if (blockListener != null) {
                    blockListener.result(params.getCurrentBlockNo(), false);
                }

                //链路成功
            } else {

                //数据成功
                if ("1".equals(uploadResponse.getRT_F())) {

                    writeTempFile(1);

                    if (blockListener != null) {
                        blockListener.result(params.getCurrentBlockNo(), true);
                    }
                    //数据失败
                } else {

                    writeTempFile(0);
                    if (blockListener != null) {
                        blockListener.result(params.getCurrentBlockNo(), false);
                    }
                }

                if (uploadResponse.getUpStatus().equals("1")) {

                    if (blockListener != null) {
                        ReturnString returnString = new ReturnString();
                        returnString.setMsg("上传成功");
                        returnString.setFileName(uploadResponse.getRT_DATA().getFileName());
                        returnString.setFilePath(uploadResponse.getRT_DATA().getFilePath());
                        blockListener.finish(true, new Gson().toJson(returnString));
                    }

                } else if (uploadResponse.getUpStatus().equals("0")) {

                    if (blockListener != null) {
                        blockListener.finish(false, uploadResponse.getRT_D());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            LogUtil.e(TAG, "解析Exception :  " + response);
            //链路失败,也许中途断网
            writeTempFile(2);
            if (blockListener != null) {
                blockListener.result(params.getCurrentBlockNo(), false);
            }
        }

    }

    /**
     * 块成功之后写入缓存文件，记录状态
     */
    private void writeTempFile(int status) {
        try {
            RandomAccessFile tempAccessFile = new RandomAccessFile(tempFilePath, "rwd");
            int blockSum = params.getBlockSum();
            long length = tempAccessFile.length();
            if (length != blockSum) {
                tempAccessFile.setLength(blockSum);
            }
            tempAccessFile.seek(currentBlockNo - 1);
            tempAccessFile.writeByte(status);
            tempAccessFile.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public interface BlockListener {
        void result(int currentBlockNo, boolean isSuccess);

        void finish(boolean success, String msg);
    }


    private String getUrl(Context context) {
        String ip, port;
        if (SharepreferenceUtil.getCommUsbEnable(context)) {
            ip = SharepreferenceUtil.getCommIpUSB(context);
            port = SharepreferenceUtil.getCommPortUSB(context);
        } else {
            ip = SharepreferenceUtil.getCommIp(context);
            port = SharepreferenceUtil.getCommPort(context);
        }
        return "http://" + ip + ":" + port + "/eomfront" + "/FrontSys/";
    }

    public void cancelRequest() {
        OkhttpUtils.getInstance().cancelRequest(params.getFileName() + params.getRangeKey());
    }

}
